﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Activities;
using HelloWorkflow;
using System.Threading;
using System.Diagnostics;

namespace HelloWorkflow.Tests
{
    [TestClass]
    public class SayHelloInCodeTest
    {
        [TestMethod]
        public void ShouldReturnGreetingWithName()
        {
            IDictionary<string, object> output;
            output = WorkflowInvoker.Invoke(new SayHelloInCode()
                                                {
                                                    UserName = "Test"
                                                }
                );


            Assert.AreEqual("Hello Test from Workflow 4", output["Greetings"]);

        }

        [TestMethod]
        public void ShouldRunActivityOnBackgroundThread()
        {
            AutoResetEvent completedEvent = new AutoResetEvent(false);

            IDictionary<string, object> output = null;

            WorkflowApplication workflowApplication = new WorkflowApplication((new SayHelloInCode()
                                                 {
                                                     UserName = "Test"
                                                 }));

            workflowApplication.Completed = (e) =>
                                                {
                                                    output = e.Outputs;

                                                    //Signal the test thread the work is done
                                                    completedEvent.Set();
                                                };

            workflowApplication.Run();

            Assert.IsTrue(completedEvent.WaitOne(TimeSpan.FromSeconds(1)), "Timeout Waiting for SayHello activity to complete");

            Assert.IsTrue(output.ContainsKey("ActivityThread"), "SayHello must return an OutArgument named ActivityThread");

            object outarg = output["ActivityThread"];

            Assert.IsInstanceOfType(outarg, typeof(Int32), "ActivityThread must be of type Int32");

            int activityThread = (Int32)outarg;

            Trace.WriteLine(string.Format("Test thread is {0}", Thread.CurrentThread.ManagedThreadId));
            Trace.WriteLine(string.Format("Activity thread is {0}", activityThread));

            Assert.IsTrue(activityThread > 0, "Invalid value for ActivityThread");

            Assert.AreNotEqual(Thread.CurrentThread.ManagedThreadId, activityThread, "Activity was not invoked on background thread");
        }
    }
}
